package com.srit.vgt.main;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.srit.vgt.entity.City;
import com.srit.vgt.entity.District;
import com.srit.vgt.entity.EcrInfo;
import com.srit.vgt.entity.Market;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Configuration
@Slf4j
public class UploadInformation extends DaoInject {




    @PostConstruct
    public void upload() {
        //{"market":{"address":"江苏省南京市栖霞区迈皋桥街道","busiNum":119,"cityId":"3201","districtId":"000001","latitude":29.836177,"longitude":121.569743,"marketId":"320113135","marketName":"上坝菜场"},"city":{"cityId":"3201","cityName":"南京市"},"EcrInfo":[{"weighNum":0,"ecrID":"00160007","statusStartTime":1609221421000,"weighPrice":0,"classifyType":1,"insertDateTime":1609138263000,"ecrType":"蔬菜","status":2}],"district":{"cityId":"0574","districtId":"000001","districtName":"栖霞区"},"tranPrice":9.600000381469727,"tranNum":1}
        log.info("start prepare data =====> {}", LocalDateTime.now().toString());
        Market market = marketDao.findAll().get(0);
        JSONObject all = new JSONObject();
        all.put("time", System.currentTimeMillis());
        all.put("market", market);
        all.put("tranNum", tranSummDao.getTranNum());
        all.put("tranPrice", tranSummDao.getTranPrice());
        District district = districtDao.getById(market.getDistrictId());
        all.put("district", district);

        City city = cityDao.getById(market.getCityId());
        all.put("city", city);


        List<EcrInfo> ecrInfos = ecrInfoDao.findAll();
        JSONArray ecrArray = new JSONArray();
        for (EcrInfo ecrInfo : ecrInfos) {
            JSONObject ecrInfoJson = JSONObject.parseObject(JSONObject.toJSONString(ecrInfo));
            ecrInfoJson.put("weighNum", weighInfoDao.getWeighNum(ecrInfo.getEcrID()));
            ecrInfoJson.put("weighPrice", weighInfoDao.getWightPrice(ecrInfo.getEcrID()));
            ecrArray.add(ecrInfoJson);
        }
        all.put("EcrInfo",ecrArray);

        File file = new File(System.getProperty("user.home") + "/Documents/NewEnvironment/model");
        if (file.listFiles() != null) {
            String models = Arrays.stream(file.listFiles()).map(File::getName).collect(Collectors.joining(","));
            all.put("models",models);
        }
        log.info(all.toJSONString());
        sendTo(all);


    }

    public void sendTo(JSONObject data) {
        String url = "http://"+this.getIp() +":8111/upload/all";
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(data.toJSONString(), MediaType.parse("application/json")))
                .build();
        Response response;
        try {
            response = okHttpClient.newCall(request).execute();
            String ip = Objects.requireNonNull(response.body()).string();
            JSONObject re = JSONObject.parseObject(ip);
            log.info("send back ==>{}",ip);
            if ("successful".equals(re.getString("message"))) {
                ip = re.getString("data");
                File file = new File("ip");
                Files.write(file.toPath(),ip.getBytes(StandardCharsets.UTF_8), StandardOpenOption.TRUNCATE_EXISTING);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getIp() {
        try {
            File file = new File("ip");
            if (file.exists()) {
                return Files.readAllLines(file.toPath()).get(0).trim();
            }
            if (file.createNewFile()) {
                Files.write(file.toPath(),"122.51.239.199".getBytes(StandardCharsets.UTF_8), StandardOpenOption.TRUNCATE_EXISTING);
            }

        } catch (IOException ignore) {
        }
        return "122.51.239.199";
    }

    public static void main(String[] args) {
        System.out.println(System.getProperty("user.home"));
    }
}
